import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title';
import { findCodes, getFirstRoute } from "@/utils/utils";
NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login', '/auth-redirect']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start();
  // 设置页面标题
  document.title = getPageTitle(to.meta.title);
  // 获取用户token
  const hasToken = getToken();
  // 如果有token
  if (hasToken) {
    // 如果路由是登录页
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' });
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      try {
        // 如果已经加载过菜单则跳过获取菜单接口
        if (!store.getters.hasMenu) {
          // 获取左侧菜单
          await store.dispatch('user/getLeftMenus');
          // 设置第一条权限路由
          const routePath = getFirstRoute(store.getters.permission_routes, store.getters.permission_routes[0].path)
          next({ path: routePath, replace: true, query: { noGoBack: true } });
        }
        // 路由转换/dashboard->dashboard
        let path = to.path.split('/').pop();
        if (path !== '401' && path !== '404') {
          // 如果路由不为登录页则获取权限code ['Create','Edit','QUery','Delete']
          let codes = findCodes(store.getters.permission_routes, path) ? findCodes(store.getters.permission_routes, path) : [];
          store.commit('user/SET_CODES', codes);
          // 如果有权限code则继续跳转,否则跳转到404
          if (codes.length > 0) {
            next()
          } else {
            // 防止内存溢出
            next({path: "/401"});
            NProgress.done();
          }
        } else {
          next()
        }
      } catch (error) {
        // remove token and go to login page to re-login
        await store.dispatch('user/resetToken');
        // Message.error(error || '获取菜单失败, 请稍后再试');
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
